<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>渐变绘制</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="600" height="600"></canvas>

  <script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");

    // 线形渐变
    if (false) {
      // 四个参数分别表示渐变线段的开始与结束点 x1, y1, x2, y2
      const linear = ctx.createLinearGradient(0, 0, 200, 200);
      // 颜色渐变过程
      linear.addColorStop(0, "red");
      linear.addColorStop(0.5, "yellow");
      linear.addColorStop(1, "purple");
      // 设置渐变
      ctx.fillStyle = linear;
      // 绘制矩形 展示渐变
      ctx.fillRect(10, 10, 200, 200);
    }

    // 径向渐变
    if (true) {
      const linear2 = ctx.createRadialGradient(100, 100, 100, 100, 100, 0);
      // 颜色渐变过程
      linear2.addColorStop(0, "white");
      // linear2.addColorStop(0.5, "yellow");
      linear2.addColorStop(1, "green");
      // 设置渐变
      ctx.fillStyle = linear2;
      // 绘制矩形 展示渐变
      ctx.fillRect(0, 0, 200, 200);
    }

  </script>
</body>

</html>